<template>
  <div>
    <el-button v-loading="btnLoading" @click="ViewTracks" type="primary"> {{$t('common.map.showTrack')}} </el-button>
    <el-dialog
      v-if="!pointsLoading"
      :title="$t('common.map.showTrack')"
      :visible.sync="Visible"
      width="500px"
      :before-close="close"
    >
      <bbx-power-map v-if="currentMapType" :init-setting="mapCenter" :current-map-type="currentMapType" ref="baseMapContainer" />
      <!-- <div ref="container" class="container"></div> -->
      <span slot="footer" class="dialog-footer">
        <el-button type="plain-third" @click="close">{{$t('common.base.close')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as TaskApi from '@src/api/TaskApi.ts';
import { useMapType } from '@src/util/map';
export default {
  name: 'base-trajectory',
  props: {
    field: {
      type: Object,
      default: () => ({}),
    },

    // 1：工单预计里程 2：实际里程
    type: {
      type: Number,
      default: 0,
    },
  },

  data() {
    return {
      Visible: false,
      containerKey: 0,
      // 轨迹标记
      points: [
        // [120.09584581, 30.26951986],
        // [102.66449, 31.30152],
        // [120.09584581, 30.26951986],
      ],
      currentMapType:null,
      pointsLoading:true,
      drawed:false,
      btnLoading: false,
    };
  },
  watch: {
    Visible(newValue) {
      if (!newValue) {
        this.pointsLoading = true
      }
    },
  },
  methods: {
    getTrack() {
      if (!this.taskId) return;
      this.btnLoading = true
      TaskApi.getTrack({
        taskId: this.taskId,
        type: this.type,
      }).then(res => {
        if (res.code === 0) {
          let markPoint = res.result?.map((item, index) => {
            return {lat:item.latitude, lng:item.longitude, markTitle:index, markInfo:`<div style='width:20px;height:20px;background-color:var( --color-primary );color:#fff;border-radius:50%;text-align:center;line-height:20px;font-size:12px;'>${index + 1}</div>`, size:{x:20, y:20 }}
          });
          this.points = markPoint
          setTimeout(() => {
            this.$refs.baseMapContainer.setListMark(this.points) 
          }, 300);
          setTimeout(() => {
            if(this.points.length > 2){
              return this.$refs.baseMapContainer.drawPolyline()
            }
            this.$refs.baseMapContainer.setMapCenter(null, this.points[0])
            this.$refs.baseMapContainer.drawDriving(this.points)
            this.drawed = true
          }, 500)
          this.Visible = true;
          
        } else {
          this.$message.error(res.message);
        }
      }).finally(()=>{
        this.pointsLoading = false
        this.btnLoading = false
      });
    },
    ViewTracks() {
      this.getTrack()
    },
    close() {
      this.Visible = false;
    },
    GetMap() {
      const map = new AMap.Map(this.$refs.container, { zoom: 13 });

      if (this.points.length < 2) {
        return;
      } else if (this.points.length === 2) {
        // 用规划
        this.Driving(map);
      } else if (this.points.length > 2) {
        // 用折现回执
        this.Polyline(map);
      }
    },
    // 已舍弃
    Driving(map) {
      AMap.plugin('AMap.Driving', () => {
        let drivingOption = {
          policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
          ferry: 1, // 是否可以使用轮渡
          map: map,
        };

        // 构造路线导航类
        let driving = new AMap.Driving(drivingOption);

        let Start = this.points[0];
        let End = this.points[1];

        driving.search(
          new AMap.LngLat(Start[0], Start[1]),
          new AMap.LngLat(End[0], End[1]),
          (status, result) => {
            // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
            } else {
            }
          }
        );
      });
    },
    Polyline(map) {
      // 绘制折现
      let path = [];
      this.points.map(item => {
        path.push([...item]);
      });
      const polyline = new AMap.Polyline({
        map: map,
        path: path,
        isOutline: true,
        outlineColor: '#1aac2d',
        borderWeight: 0,
        strokeColor: '#1aac2d',
        strokeOpacity: 1,
        strokeWeight: 6,
        strokeStyle: 'solid',
        lineJoin: 'round',
        lineCap: 'round',
        zIndex: 50,
        showDir: true,
      });

      // 起始标记点
      let Start = this.points[0];
      let StartIcon = new AMap.Icon({
        size: new AMap.Size(40, 50), // 图标尺寸
        image: 'https://file.shb.ltd/shb-resource/amap/core.png', // Icon的图像
        imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(40, 50), // 根据所设置的大小拉伸或压缩图片
      });
      const StartMarker = new AMap.Marker({
        position: new AMap.LngLat(Start[0], Start[1]),
        offset: new AMap.Pixel(-10, -10),
        zoom: 13,
        // icon: StartIcon,
      });
      map.add(StartMarker);

      let End = this.points.slice(-1)[0]
      let EndtIcon = new AMap.Icon({
        size: new AMap.Size(40, 50), // 图标尺寸
        image: 'https://file.shb.ltd/shb-resource/amap/core.png', // Icon的图像
        imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(40, 50), // 根据所设置的大小拉伸或压缩图片
      });
      const EndMarker = new AMap.Marker({
        position: new AMap.LngLat(End[0], End[1]),
        offset: new AMap.Pixel(-10, -10),
        zoom: 13,
        // icon: EndtIcon,
      });
      map.add(EndMarker);

      map.setFitView();
    },
  },

  computed: {
    taskId() {
      return this.$route.params.id;
    },
    mapCenter(){
      return this.points?.[0] || {}
    },
  },
  async created(){
    const { currentMapType } = await useMapType();
    this.currentMapType = currentMapType()
  },
  mounted() {},
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 300px;
}
</style>
